<template>
  <div>
    <!-- 页面标题栏 -->
    <div class="page-header" style="margin-bottom: 20px;">
      <h2 style="color: #409EFF; font-size: 20px; margin-bottom: 0;">订单管理</h2>
    </div>
    
    <!-- 搜索区域 -->
    <div class="flex items-center mb-4">
      <el-input 
        v-model="searchOrderId" 
        placeholder="请输入订单编号" 
        @keyup.enter="fetchOrders" 
        class="flex-1 custom-input"
        size="default"
        :prefix-icon="Search"
      />
    </div>
    
    <!-- 订单表格 -->
    <el-card shadow="hover" class="mb-6" style="border-radius: 4px;">
      <el-table 
        :data="orders" 
        stripe 
        border="false"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        header-row-class-name="table-header"
        class="custom-table"
      >
        <el-table-column prop="orderId" label="订单编号" align="center" min-width="180" />
        <el-table-column prop="payer" label="创建人" align="center" min-width="100" />
        <el-table-column prop="createTime" label="下单时间" align="center" min-width="160" />
        <el-table-column prop="updateTime" label="更新时间" align="center" min-width="160" />
        <el-table-column prop="status" label="订单状态" align="center" min-width="100">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.status === '待支付'" 
              type="info" 
              size="small"
            >
              待支付
            </el-tag>
            <el-tag 
              v-else-if="scope.row.status === '已支付'" 
              type="primary" 
              size="small"
            >
              已支付
            </el-tag>
            <el-tag 
              v-else-if="scope.row.status === '配送中'" 
              type="warning" 
              size="small"
            >
              配送中
            </el-tag>
            <el-tag 
              v-else-if="scope.row.status === '已完成'" 
              type="success" 
              size="small"
            >
              已完成
            </el-tag>
            <el-tag 
              v-else-if="scope.row.status === '已取消'" 
              type="danger" 
              size="small"
            >
              已取消
            </el-tag>
            <el-tag 
              v-else-if="scope.row.status === '取消中'" 
              type="warning" 
              size="small"
            >
              取消中
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="80" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="showOrderDetails(scope.row)"
              :icon="View"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      />
    </div>
    
    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="订单详情"
      width="700px"
      center
    >
      <!-- 设置 label-position 为 left 让标签左对齐 -->
      <el-form ref="orderFormRef" :model="orderDetails" label-width="120px" label-position="left" :rules="rules">
        <el-form-item label="订单编号">
          <el-input v-model="orderDetails.orderId" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="总金额">
          <el-input v-model="orderDetails.totalPrice" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="当前状态">
          <el-input v-model="orderDetails.status" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="下单时间">
          <el-input v-model="orderDetails.createTime" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="orderDetails.updateTime" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="orderDetails.address" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="orderDetails.payer" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="orderDetails.phone" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="收件人">
          <el-input v-model="orderDetails.name" disabled style="background-color: #f5f7fa;" />
        </el-form-item>
        <el-form-item label="快递单号" prop="trackingNo">
          <el-input 
            v-model="orderDetails.trackingNo" 
            :disabled="!!initialTrackingNo" 
            placeholder="请输入快递单号" 
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="orderDetails.remark" 
            type="textarea" 
            :rows="3"
            disabled 
            style="background-color: #f5f7fa;" 
            placeholder="用户订单备注"
          />
        </el-form-item>
        <el-form-item label="修改状态" prop="newStatus">
          <el-select v-model="orderDetails.newStatus" placeholder="请选择新状态" :disabled="orderDetails.status === '已完成'">
            <el-option label="待支付" value="待支付"></el-option>
            <el-option label="已支付" value="已支付"></el-option>
            <el-option label="配送中" value="配送中"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <!-- 订单商品列表 -->
      <div style="margin-top: 20px;">
        <h3 style="color: #409EFF; margin-bottom: 10px;">商品列表</h3>
        <el-table :data="orderDetails.product" stripe border style="width: 100%">
          <el-table-column prop="productName" label="商品名称" align="center" min-width="200" />
          <el-table-column prop="price" label="单价" align="center" min-width="100" />
          <el-table-column prop="dict" label="单位" align="center" min-width="80" />
          <el-table-column prop="quantity" label="数量" align="center" min-width="80" />
        </el-table>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">返回</el-button>
          <el-button type="primary" @click="updateOrderStatus">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axiosInstance from '../axiosInstance';
import { ElMessageBox } from 'element-plus';
import { Search, View } from '@element-plus/icons-vue';

const searchOrderId = ref('');
const orders = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const loading = ref(false);
const orderDetails = ref({
  orderId: '',
  totalPrice: '',
  status: '',
  createTime: '',
  updateTime: '',
  newStatus: '',
  product: [],
  address: '',
  payer: '',
  phone: '',
  name: '',
  trackingNo: '',
  remark: ''
});
// 用于存储初始的快递单号状态，判断是否为新增
const initialTrackingNo = ref('');
const orderFormRef = ref(null);

// 表单验证规则
const rules = reactive({
  newStatus: [
    { required: true, message: '请选择订单状态', trigger: 'change' }
  ],
  trackingNo: [
    { min: 6, max: 30, message: '快递单号长度在 6 到 30 个字符', trigger: 'blur' }
  ]
});

const fetchOrders = async () => {
  loading.value = true;
  try {
    const requestData = {
      orderId: searchOrderId.value,
      page: currentPage.value,
      pageSize: pageSize.value
    };
    const response = await axiosInstance.post('/order/adminList', requestData);
    if (response.data.code === '200') {
      orders.value = response.data.data.listData;
      total.value = Number(response.data.data.total);
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if(error.response){
      const { status } = error.response;
      if (status === 401) {
        return;
      }
    }
    console.error(error);
    ElMessageBox.alert('获取订单列表失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  } finally {
    loading.value = false;
  }
};

const showOrderDetails = async (order) => {
  try {
    const response = await axiosInstance.get(`/order/detail/${order.orderId}`);
    if (response.data.code === '200') {
      const data = response.data.data;
      // 保存初始的快递单号状态
      initialTrackingNo.value = data.trackingNo || '';
      orderDetails.value = {
        orderId: data.orderId,
        totalPrice: data.totalAmount,
        status: data.status,
        createTime: data.createTime,
        updateTime: data.updateTime,
        newStatus: data.status,
        product: data.items,
        address: data.address,
        payer: data.payer,
        phone: data.phone,
        name: data.name || '',
        trackingNo: data.trackingNo || '',
        remark: data.remark || ''
      };
      dialogVisible.value = true;
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    console.error(error);
    ElMessageBox.alert('获取订单详情失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const updateOrderStatus = async () => {
  if (orderDetails.value.status === '已完成') {
    ElMessageBox.alert('订单已完成，无法修改状态', '提示', {
      confirmButtonText: '确定',
      type: 'warning',
      customClass: 'center-message-box'
    });
    return;
  }
  
  try {
    // 验证表单
    await orderFormRef.value.validate();
    
    const orderId = orderDetails.value.orderId;
    const requestData = {
      orderId,
      newStatus: orderDetails.value.newStatus,
      trackingNo: orderDetails.value.trackingNo
    };
    const response = await axiosInstance.post('/order/updateStatus', requestData);
    if (response.data.code === '200') {
      ElMessageBox.alert('订单状态更新成功', '提示', {
        confirmButtonText: '确定',
        type: 'success',
        customClass: 'center-message-box'
      });
      handleCloseDialog();
      fetchOrders();
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if (error === false) {
      return;
    }
    console.error(error);
    ElMessageBox.alert('更新订单状态失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchOrders();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchOrders();
};

// 关闭对话框
const handleCloseDialog = () => {
  if (orderFormRef.value) {
    orderFormRef.value.resetFields();
  }
  dialogVisible.value = false;
  initialTrackingNo.value = '';
};

fetchOrders();
</script>

<style scoped>
.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 1rem;
}

.flex-1 {
  flex: 1;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* 表格头部样式 */
.table-header {
  background-color: #f5f7fa;
  color: #409EFF;
}

/* 让消息框居中的样式 */
.center-message-box .el-message-box {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 表单样式调整 */
.el-form-item__label {
  text-align: left !important;
}

.el-form-item__content {
  margin-left: 120px !important;
}

/* 动画效果 */
.el-button {
  transition: all 0.3s ease;
}

.el-table {
  transition: box-shadow 0.3s ease;
}

.el-card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 禁用输入框样式优化 */
.el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa !important;
}

/* 输入框自定义样式 */
:deep(.custom-input) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
  &:hover {
    border-color: #c0c4cc;
  }
  &:focus {
    border-color: #409EFF;
    outline: none;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}

/* 表格自定义样式 */
:deep(.custom-table) {
  .el-table__cell {
    border-color: #ebeef5;
  }
  .el-table__header-wrapper {
    .el-table__header {
      .el-table__cell {
        background-color: #f5f7fa;
        color: #409EFF;
        font-weight: 500;
      }
    }
  }
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
    .el-table__cell {
      color: #606266;
    }
  }
}
</style>